package com.ihunanren.webx.pipeline;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.alibaba.citrus.service.pipeline.PipelineContext;
import com.alibaba.citrus.service.pipeline.support.AbstractValve;
import com.alibaba.citrus.service.pipeline.support.AbstractValveDefinitionParser;
import com.alibaba.citrus.springext.util.SpringExtUtil;
import com.ihunanren.common.auth.MD5;
import com.ihunanren.webx.SessionKeeper;
/**
 * 淘宝jssdk集成的三个cookie
 * @author kalman03
 */
public class TaobaoJssdkSignValve extends AbstractValve {

	private static String timestamp = String.valueOf(System.currentTimeMillis());
	
	@Autowired
	private HttpServletResponse response;
	
	private String appkey;
	private String secret;
	
	@Override
	public void invoke(PipelineContext pipelineContext) throws Exception {
		Cookie c1 = new Cookie(SessionKeeper.OPEN_TAOBAO_COOKIE_TIMESTAMP, timestamp);
		c1.setPath("/");
		
		String originalSign = getOriginalSign();
		
		Cookie c2 = new Cookie(SessionKeeper.OPEN_TAOBAO_COOKIE_SIGN,MD5.getSign(secret,originalSign));
		c2.setPath("/");
		
		Cookie c3 = new Cookie(SessionKeeper.OPEN_TAOBAO_COOKIE_ORIGNALSIGN, originalSign);
		c3.setPath("/");
		
		HttpServletResponse resp =(HttpServletResponse)response;
		resp.addCookie(c1);
		resp.addCookie(c2);
		resp.addCookie(c3);
		
		pipelineContext.invokeNext();
	}
	
	public static class DefinitionParser extends AbstractValveDefinitionParser<TaobaoJssdkSignValve> {
		@Override
		protected void doParse(Element element, ParserContext parserContext,BeanDefinitionBuilder builder) {
			SpringExtUtil.attributesToProperties(element, builder, "appkey", "secret");
		}
	}
	
	/**
	 * $secret.'app_key'.$app_key.'timestamp'.$timestamp.$secret
	 * @return
	 */
	private String getOriginalSign() {
		StringBuilder signStr = new StringBuilder();
		signStr.append(secret).append("app_key").append(appkey)
				.append("timestamp").append(timestamp).append(secret);
		return signStr.toString();
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}
	public void setSecret(String secret) {
		this.secret = secret;
	}
	
}
